package ru.xpparty.scanner;

import java.io.IOException;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: vanger
 * Date: 19.12.10
 * Time: 13:00
 * To change this template use File | Settings | File Templates.
 */
public class ScannerImpl implements Scanner {
    private static final int MAX_PORT = 65537;
    private static final int MIN_PORT = 0;

    private boolean isOpen(String host, int port) {
        try {
            new Socket(host, port);
        } catch (IOException e) {
            return false;
        }

        return true;
    }

    public boolean isValid(int port) {
        return port > MIN_PORT && port <= MAX_PORT;

    }

    @Override
    public Map<Host, ResultEnum> scanRange(Collection<Host> adrs) {
        Map<Host, ResultEnum> result = new HashMap<Host, ResultEnum>();
        for (Host host : adrs) {
            result.put(host, scanPort(host));
        }
        return result;
    }

    @Override
    public ResultEnum scanPort(Host host) {
        if (!isValid(host.getPort())) return ResultEnum.INVALID;
        return isOpen(host.getIp(), host.getPort()) ? ResultEnum.OPENED : ResultEnum.CLOSED;
    }


}
